var api = require('../config/api.js')

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatDate(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  if (month < 10) {
    month = "0" + month.toString();
  }
  var day = date.getDate();
  if (day < 10) {
    day = "0" + day.toString();
  }
  return year + '-' + month + '-' + day;
}

function formatTime2(date) {
  var hour = date.getHours();
  if (hour < 10) {
    hour = "0" + hour.toString();
  }
  var minute = date.getMinutes();
  if (minute < 10) {
    minute = "0" + minute.toString();
  }
  return hour + ':' + minute;
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET", contentType = "application/json;charset=UTF-8") {
  return new Promise(function (resolve, reject) {
    if (url.indexOf("uac/oauth/token") > -1){
      contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
    }
    if (data.access_token != null && data.access_token.length > 0){
      if (url.indexOf("?") > -1) {
        url = url + "&access_token=" + data.access_token;
      } else {
        url = url + "?access_token=" + data.access_token;
      }
    }
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': contentType,
        'X-HandShake-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        //console.log(res);

        if (res.statusCode == 200) {
          resolve(res.data);
        }
        /*else if (res.statusCode == 401) {
          //需要登录后才可以操作

          let code = null;
          return login().then((res) => {
            code = res.code;
            return getUserInfo();
          }).then((userInfo) => {
            //登录远程服务器
            request(api.fetchToken(), {}, 'POST').then(res => {
              if (res.errno === 0) {
                //存储用户信息
                //wx.setStorageSync('userInfo', res.data.userInfo);
                wx.setStorageSync('token', res.data.token);

                resolve(res);
              } else {
                reject(res);
              }
            }).catch((err) => {
              reject(err);
            });
          }).catch((err) => {
            reject(err);
          })
        }*/
        else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

function get(url, data = {} , contentType = "application/json;charset=UTF-8") {
  return request(url, data, 'GET', contentType)
}

function post(url, data = {}, contentType = "application/json;charset=UTF-8") {
  return request(url, data, 'POST', contentType)
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          resolve(res.code);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        console.log(res);
        if (res.detail.errMsg === 'getUserInfo:ok') {
          resolve(res);
        } else {
          reject(res)
        }
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}

module.exports = {
  formatTime,
  formatTime2,
  formatDate,
  request,
  get,
  post,
  redirect,
  showErrorToast,
  checkSession,
  login,
  getUserInfo,
  digitalFormatTime,
  dialogAlert,
  showToast,
  getVideoFileMaxTime,
  getVideoFileMaxSize,
  getAudioFileMaxTime,
  getShareType,
  fileLegalSuffix,
  getDateStr,
  getDateHHMMStr,
  haveSomeMinutesTime,
  addZoreDate,
  downloadImage
}

/**
 * 文件的合法后缀名：用于从微信获取文件时的校验
 */
function fileLegalSuffix() {
  var value = ["doc", "docx", "pdf", "xlsx", "xls", "ppt", "pptx"];
  return value;
}

/**
 * 数字转换为时间
 */
function digitalFormatTime(e) {
  var hourSize = 1 * 60 * 60;
  var minuteSize = 1 * 60;
  if (e > hourSize) {
    var hour = parseInt(e / hourSize);
    var minute = parseInt(e / minuteSize);
    var second = e % minuteSize;
    if (hour < 10) {
      hour = "0" + parseInt(hour);
    }
    if (minute < 10) {
      minute = "0" + parseInt(minute);
    }
    if (second < 10) {
      second = "0" + parseInt(second);
    }
    return hour + ":" + minute + ":" + second;
  } else if (e > minuteSize) {
    var minute = parseInt(e / minuteSize);
    var second = e % minuteSize;
    if (minute < 10) {
      minute = "0" + parseInt(minute);
    }
    if (second < 10) {
      second = "0" + parseInt(second);
    }
    return minute + ":" + second;
  } else {
    if (e < 10) {
      e = "0" + parseInt(e);
    }
    return "00:" + e;
  }
}

/**
 * Dialog弹窗
 */
function dialogAlert(e) {
  wx.showToast({
    title: e,
    icon: 'none',
    duration: 2000
  })

  setTimeout(function () {
    wx.hideToast()
  }, 2000)
}

/**
 * 带有图标的弹窗
 */
function showToast(title, e = "success"){
  wx.showToast({
    title: title,
    icon: e,
    duration: 2000
  })
}

/**
 * 视频录制时长：单位（秒）
 */
function getVideoFileMaxTime(key) {
  var info = { "diary": 10, "circle": 10, "theme": 10 };
  return info[key];
}

/**
 * 视频录制大小:单位（M）
 */
function getVideoFileMaxSize(key) {
  var info = { "diary": 10, "circle": 10, "theme": 10 };
  return info[key];
}

/**
 * 音频录制时长:单位（毫秒）
 */
function getAudioFileMaxTime(key) {
  var info = { "diary": 600000, "albumInfo": 600000, "diaryReview": 600000, "diaryComments": 600000, "circle": 600000, "theme": 600000 };
  return info[key];
}

/**
 * 分享类型
 */
function getShareType(key) {
  var info = { "circle": 1, "diary": 2, "helpSign": 3, "groupbuyTicket": 4, "examplesTicket": 5, "commissionCircle": 6};
  return info[key];
}

/**
 * 传入时间和添加天数获取后几天或前几天
 */
function getDateStr(today, addDayCount) {
  var dd;
  if (today) {
    dd = new Date(today);
  } else {
    dd = new Date();
  }
  dd.setDate(dd.getDate() + addDayCount);//获取AddDayCount天后的日期 
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;//获取当前月份的日期 
  var d = dd.getDate();
  if (m < 10) {
    m = '0' + m;
  };
  if (d < 10) {
    d = '0' + d;
  };
  return y + "-" + m + "-" + d;
}

/**
 * 传入时间和添加天数获取后几天或前几天
 */
function getDateHHMMStr(today, addDayCount) {
  var dd;
  if (today) {
    dd = new Date(today);
  } else {
    dd = new Date();
  }
  dd.setDate(dd.getDate() + addDayCount);//获取AddDayCount天后的日期 
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;//获取当前月份的日期 
  var d = dd.getDate();
  var h = dd.getHours();
  var mm = dd.getMinutes();
  if (m < 10) {
    m = '0' + m;
  };
  if (d < 10) {
    d = '0' + d;
  };
  if (h < 10) {
    h = '0' + h;
  };
  if (mm < 10) {
    mm = '0' + mm;
  };
  return y + "-" + m + "-" + d + " " + h + ":" + mm;
}

//获取根据当前时候的后几分钟或前几分钟
function haveSomeMinutesTime(n) {
  if (n == null) {
    n = 0;
  }
  // 时间
  var newDate = new Date()
  // var timeStamp = newDate.getTime(); //获取时间戳
  var date = newDate.setMinutes(newDate.getMinutes() + n);
  newDate = new Date(date);
  var year = newDate.getFullYear();
  var month = newDate.getMonth() + 1;
  var day = newDate.getDate();
  var h = newDate.getHours();
  var m = newDate.getMinutes();
  var s = newDate.getSeconds();
  if (h < 10) {
    h = '0' + h;
  };
  if (m < 10) {
    m = '0' + m;
  };
  var time = year + "年" + month + "月" + day + "日 " + h + ":" + m;
  return time;
}

//加0转换格式
function addZoreDate(n) {
  // 时间
  var newDate = new Date(n)
  // var timeStamp = newDate.getTime(); //获取时间戳
  var year = newDate.getFullYear();
  var month = newDate.getMonth() + 1;
  var day = newDate.getDate();
  var h = newDate.getHours();
  var m = newDate.getMinutes();
  var s = newDate.getSeconds();
  if (month < 10) {
    month = '0' + month;
  };
  if (day < 10) {
    day = '0' + day;
  };
  if (h < 10) {
    h = '0' + h;
  };
  if (m < 10) {
    m = '0' + m;
  };
  var time = year + "年" + month + "月" + day + "日 " + h + ":" + m;
  return time;
}

function downloadImage(imageUrl) {
  // 下载文件  
  wx.downloadFile({
    url: imageUrl,
    success: function (res) {
      // 保存图片到系统相册  
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          wx.showToast({
            title: '保存成功',
          });
        },
        fail(res) {
          console.log("保存图片：fail");
          console.log(res);
        }
      })
    },
    fail: function (res) {
      console.log("下载文件：fail");
      console.log(res);
    }
  })
}